/**
 * Copyright (c) 2018 苍穹跃龙
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.l.core.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.baomidou.mybatisplus.plugins.Page;
import com.l.web.master.system.entity.SysUser;

/**
 * @author 严秋旺
 * @date 2018-09-23
 */
public class WebUtils {
    public static final String SESSION_LOGIN = "s_user";

    public static HttpServletRequest getRequest() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        if (attributes == null) {
            return null;
        }

        return ((ServletRequestAttributes) attributes).getRequest();
    }

    public static <T> Page<T> getPage() {
        HttpServletRequest request = getRequest();
        String pageNumber = request.getParameter("pageNumber");
        String pageSize = request.getParameter("pageSize");
        int current = 1;
        int size = 10;

        if (StringUtils.isNotEmpty(pageSize)) {
            try {
                size = Integer.parseInt(pageSize);
            } catch (Exception e) {
                // ignore
            }
        }

        if (StringUtils.isNotEmpty(pageNumber)) {
            try {
                current = Integer.parseInt(pageNumber);
            } catch (Exception e) {
                // ignore
            }
        }

        Page<T> page = new Page<>(current, size);
        return page;
    }

    public static void setLogin(SysUser user) {
        HttpSession session = getRequest().getSession();
        session.setAttribute(SESSION_LOGIN, user);
    }

    public static SysUser getLogin() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }

        HttpSession session = request.getSession();
        return (SysUser) session.getAttribute(SESSION_LOGIN);
    }
}
